package kr.ac.kaist.pointdaproject;

import android.app.ListFragment;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class CardListAllFragment extends ListFragment {

	private static final String SORT_ORDER = "(name)asc";
	
	Cursor mC;
	ContentResolver mResolver;
	Uri mUri;
	
	
	public static CardListAllFragment newInstance() {
		CardListAllFragment fragment = new CardListAllFragment();
		return fragment;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mUri = PointCard.Cards.CONTENT_URI;
		mResolver = getActivity().getContentResolver();
		mC = mResolver.query(mUri, null, null, null, SORT_ORDER);

		if(mC.getCount() == 0)
		{
			setEmptyText(getResources().getText(R.string.no_card));
		}
		
		CardListCustomAdapter adapter = new CardListCustomAdapter(getActivity(), mC);
		setListAdapter(adapter);
	}

	@Override
	public void onResume() {

		mC = mResolver.query(mUri, null, null, null, SORT_ORDER);

		if(mC.getCount() == 0)
		{
			setEmptyText(getResources().getText(R.string.no_card));
		}
		
		CardListCustomAdapter adapter = new CardListCustomAdapter(getActivity(), mC);
		setListAdapter(adapter);

		super.onResume();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Uri uri = ContentUris.withAppendedId(PointCard.Cards.CONTENT_URI, id);

		Intent intent = new Intent(getActivity(), CardDetail.class);
		intent.setData(uri);
		
		startActivity(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mC.close();
	}
}


